﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace TMWS.Utilities
{
	/// <summary>
	/// Log utlity
	/// </summary>
	public class Log
	{
		#region Fields

		/// <summary>
		/// The _logFileName
		/// </summary>
		private static string _logFileName = "TMWS.NET_log_{0}.txt";

		/// <summary>
		/// The _logFileDirectory
		/// </summary>
		private static string _logFileDirectory;

		#endregion

		#region Public Methods

		/// <summary>
		/// Creates a new log file
		/// </summary>
		public static void Create()
		{
			string fileName = GetLogFile();

			if (!Directory.Exists(_logFileDirectory))
			{
				// Create directory
				Directory.CreateDirectory(_logFileDirectory);
			}

			if (!File.Exists(fileName))
			{
				// Create a new log file
				File.Open(fileName, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite);
			}
		}

		/// <summary>
		/// Adds a log entry
		/// </summary>
		/// <param name="text">Message to log</param>
		public static void AddEntry(string text)
		{
			string logEntry = DateTime.Now.ToString() + " => " + text;

			Create(); // Create

			using (StreamWriter writer = File.AppendText(GetLogFile()))
			{
				// Write to log
				writer.WriteLine(logEntry);
			}
		}

		/// <summary>
		/// Adds a log entry
		/// </summary>
		/// <param name="text">Message to log</param>
		/// <param name="args">Formatting arguments</param>
		public static void AddEntry(string text, params object[] args)
		{
			string entryText = String.Format(text, args);

			// Add formatted entry
			AddEntry(entryText);
		}

		/// <summary>
		/// Gets the log file name
		/// </summary>
		/// <returns>Log file path</returns>
		private static string GetLogFile()
		{
			string fileName = _logFileDirectory + String.Format(_logFileName, DateTime.Today.ToShortDateString());

			return fileName;
		}

		#endregion

		#region Properties

		/// <summary>
		/// Gets or sets the log directory
		/// </summary>
		public static string LogDirectory
		{
			get { return _logFileDirectory;}
			set { _logFileDirectory = value; }
		}

		#endregion
	}
}